package vsm.vsm_server.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.CreateUploadImageResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import vsm.vsm_server.pojo.Image.ImageInfo;
import vsm.vsm_server.pojo.Result.Result;
import vsm.vsm_server.pojo.Result.ResultEnum;
import vsm.vsm_server.service.ImageService;
import vsm.vsm_server.service.VodService;

import java.util.concurrent.TimeUnit;

import static vsm.vsm_server.component.oss.InitAcsClint.*;

@Slf4j
@RestController
@RequestMapping("/image")
@CrossOrigin
public class ImageController {
    @Autowired
    ImageService imageService;

    @Autowired
    private VodService vodService;

    @Autowired
    private StringRedisTemplate redisTemplate; // 注入 Redis 模板
    @PostMapping("/create")
    public Result<CreateUploadImageResponse> create(@RequestBody ImageInfo imageInfo){
        String accessKeyId ="LTAI5tEdXUnEBu5V7sQVnkJs";
        String accessKeySecret = "PRYEoatScwy8LlRROPbaRJ0DYxtdr9";
        try{
            DefaultAcsClient client = initVodClient(accessKeyId,accessKeySecret);
            CreateUploadImageResponse response = new CreateUploadImageResponse();
            response = createUploadImage(client,imageInfo);
            System.out.print("ImageId = " + response.getImageId() + "\n");
            System.out.print("UploadAddress = " + response.getUploadAddress() + "\n");
            System.out.print("UploadAuth = " + response.getUploadAuth() + "\n");
            System.out.print("RequestId = " + response.getRequestId() + "\n");

            String imageId = response.getImageId();
            if (imageId != null && !imageId.isEmpty()) {
                // --- 存储映射关系到 Redis ---
                String s = JSON.toJSONString(imageInfo);
                String redisKey = "image_upload_info:" + imageId;
                redisTemplate.opsForValue().set(redisKey,s,1, TimeUnit.HOURS); //1h 过期

            } else {
                log.error("VOD 返回的 ImageId 为空，无法暂存信息");
                throw new Exception();
            }




            return Result.success(response);
        }catch (Exception e) {
            log.error("ErrorMessage ={}" ,e.getLocalizedMessage());
            return Result.error_special(ResultEnum.OSS_UP_WRONG);
        }
    }

    /*
   根据id获取图片url
    */
    @GetMapping("/getUrl/{imageId}")
    public Result<String> getUrl(@PathVariable String imageId){
        String imageUrl = vodService.getPicture(imageId);
        if(imageUrl !=null){
            return Result.success(imageUrl);
        }else{
            return Result.error_special(ResultEnum.VIDEO_URL_NOT_EXIST);
        }

    }

}
